package com.sparrow.common.ai.behaviortree.task.impl;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.def.BTNodeStatus;
import com.sparrow.common.ai.behaviortree.monitor.BTMonitor;
import com.sparrow.common.ai.behaviortree.task.BehaviorTask;

import java.util.List;

public class ConditionDecorateTask extends BehaviorTask {

    private final List<ConditionTask> conditionTasks;
    private final BehaviorTask targetTask;
    private boolean value;

    public ConditionDecorateTask(List<ConditionTask> conditionTasks, BehaviorTask targetTask, boolean conditon) {
        this.conditionTasks = conditionTasks;
        this.targetTask = targetTask;
        this.value = conditon;
    }

    @Override
    public BTNodeStatus tick(BehaviorContext context, long now, long delta) {
        enterTick(context);

        boolean pass = conditionTasks.isEmpty() ||
                conditionTasks.stream().allMatch(c -> {
                    boolean check = c.check(context);
                    if (c.isValue() == false) {//配置的条件值是要取反的
                        check = !check;
                    }
                    BTMonitor monitor = context.getMonitor();
                    if (monitor != null) {
                        monitor.checkCondition(context, c, check);
                    }
                    return check;
                });
        if (pass) {
            return targetTask.tick(context, now, delta);
        } else  {
            return BTNodeStatus.FAILURE;
        }
    }

    @Override
    public String toString() {
        return "ConditionDecorateTask{" +
                "conditionTasks=" + conditionTasks +
                ", targetTask=" + targetTask +
                ", condition=" + value +
                '}';
    }
}
